import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Avatar, Statistic, Badge, Table } from 'antd';
import {
  UserOutlined,
  BookOutlined,
  ScheduleOutlined,
  StarOutlined,
} from '@ant-design/icons';
import useAuthStore from '../../stores/authStore';
import { teacherAPI } from '../../services/teacher';
import './index.less';
import request from '../../utils/request';
import moment from 'moment';
import 'moment/locale/zh-cn';  // 使用中文语言包

const Dashboard = () => {
  const { user } = useAuthStore();
  const [statistics, setStatistics] = useState(null);
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(false);

  // 获取统计数据
  const fetchStatistics = async (teacherId) => {
    try {
      const res = await teacherAPI.getStatistics(teacherId);
      if (res.code === 0) {
        // 保留现有的 todayBookings
        setStatistics(prev => ({
          ...prev,
          totalCourses: res.data.totalCourses,
          averageRating: res.data.averageRating
        }));
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  // 获取预约数据
  const fetchBookings = async (teacherId) => {
    try {
      setLoading(true);
      
      const today = moment();
      const monday = moment().startOf('isoWeek');
      const sunday = moment().endOf('isoWeek');

      const res = await request.get('/api/teacher/bookings', {
        params: {
          teacherId: teacherId,
          dateFrom: monday.format('YYYY-MM-DD'),
          dateTo: sunday.format('YYYY-MM-DD')
        }
      });

      if (res.code === 0) {
        // 计算今日预约数
        const todayBookings = res.data.filter(booking => {
          const bookingDate = moment(booking.created_at).format('YYYY-MM-DD');
          const todayDate = today.format('YYYY-MM-DD');
          const isToday = bookingDate === todayDate;

          return isToday;
        });

        // 只更新 todayBookings 和 totalStudents
        setStatistics(prev => ({
          ...prev,
          todayBookings: todayBookings.length,
          totalStudents: new Set(res.data.map(booking => booking.contact_name)).size
        }));

        const scheduleData = convertBookingsToSchedule(res.data);
        setBookings(scheduleData);
      }
    } catch (error) {
      console.error('获取预约数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 将预约数据转换为课程表格式
  const convertBookingsToSchedule = (bookingData) => {
    const timeSlots = [
      '09:00-10:30',
      '10:30-12:00',
      '14:00-15:30',
      '15:30-17:00',
      '19:00-20:30'
    ];

    return timeSlots.map((timeSlot, index) => {
      const row = { 
        key: `time-${index}`,
        timeSlot 
      };
      
      ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].forEach(day => {
        const booking = bookingData.find(b => {
          const matchTimeSlot = b.time_slot === timeSlot;
          const matchDay = getDayOfWeek(b.booking_date) === day;
          return matchTimeSlot && matchDay;
        });

        if (booking) {
          row[day] = {
            key: `booking-${booking.id}`,
            type: getStatusType(booking.status),
            content: `${booking.course_title}（${getStatusText(booking.status)}）`,
            name: booking.contact_name || '待定',
            phone: booking.contact_phone || '暂无电话'
          };
        }
      });
      return row;
    });
  };

  // 获取日期对应的星期
  const getDayOfWeek = (dateString) => {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    // 使用 moment 处理时区问题
    const date = moment(dateString).local();
    return days[date.day()];
  };

  // 获取状态对应的类型
  const getStatusType = (status) => {
    const statusMap = {
      'upcoming': 'warning',
      'confirmed': 'success',
      'completed': 'success',
      'cancelled': 'error',
      'ongoing': 'processing',
    };
    return statusMap[status] || 'default';
  };

  // 获取状态对应的文本
  const getStatusText = (status) => {
    const statusMap = {
      'upcoming': '待上课',
      'confirmed': '已确认',
      'completed': '已上课',
      'cancelled': '已取消',
      'ongoing': '进行中',
    };
    return statusMap[status] || status;
  };

  // 修改 useEffect，确保两个请求的顺序
  useEffect(() => {
    if (user?.id) {
      // 使用实际的用户 ID
      fetchStatistics(user.id);
      fetchBookings(user.id);
    }
  }, [user]);

  // 表格列配置
  const columns = [
    {
      title: '时间段',
      dataIndex: 'timeSlot',
      key: 'timeSlot',
      width: 120,
      fixed: 'left',
    },
    ...['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map(day => ({
      title: day,
      dataIndex: day,
      key: day,
      width: 200,
      render: (course) => {
        if (!course) return null;
        return (
          <div className="course-cell" key={course.key}>
            <Badge
              status={course.type}
              text={
                <div>
                  <div>{course.content}</div>
                  <div className="contact-info">
                    <div>{course.name}</div>
                    <div className="phone">{course.phone}</div>
                  </div>
                </div>
              }
            />
          </div>
        );
      },
    })),
  ];

  return (
    <div className="dashboard">
      <Row gutter={[16, 16]}>
        {/* 用户信息卡片 */}
        <Col span={24}>
          <Card hoverable>
            <div className="user-info">
              <Avatar size={64} icon={<UserOutlined />} src={user?.avatar} />
              <div className="user-details">
                <h2>欢迎回来，{user?.name || '老师'}</h2>
                <p>{user?.title || '高级教师'}</p>
              </div>
            </div>
          </Card>
        </Col>

        {/* 统计数据 */}
        <Col xs={24} sm={12} md={6}>
          <Card hoverable className="stats-card">
            <Statistic
              title="总课程数"
              value={statistics?.totalCourses || 0}
              prefix={<BookOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable className="stats-card">
            <Statistic
              title="总学生数"
              value={statistics?.totalStudents || 0}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable className="stats-card">
            <Statistic
              title="今日预约"
              value={statistics?.todayBookings || 0}
              prefix={<ScheduleOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable className="stats-card">
            <Statistic
              title="平均评分"
              value={statistics?.averageRating || 0}
              precision={1}
              prefix={<StarOutlined />}
              suffix="/5"
            />
          </Card>
        </Col>

        {/* 课程表 */}
        <Col span={24}>
          <Card 
            hoverable 
            title="本周课程表"
            extra={
              <div style={{ fontSize: '12px', color: 'rgba(0,0,0,0.45)' }}>
                <Badge status="success" text="已上课" style={{ marginRight: '12px' }} />
                <Badge status="processing" text="进行中" style={{ marginRight: '12px' }} />
                <Badge status="warning" text="待上课" style={{ marginRight: '12px' }} />
                <Badge status="error" text="已取消" />
              </div>
            }
          >
            <Table
              columns={columns}
              dataSource={bookings}
              pagination={false}
              scroll={{ x: 1500 }}
              bordered
              size="middle"
              loading={loading}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard; 